package org.firebug.spring.boot.jackson.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * 百分比显示(保留1位,四舍五入): 0.12345 -> 12.3%
 * @Author: 张晓东
 */
public class Percentage1Serializer extends JsonSerializer<BigDecimal> {
    private static final String PATTERN = "##.#";
    private static final BigDecimal HUNDRED = new BigDecimal(100);

    @Override
    public void serialize(BigDecimal decimal, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        String value = new DecimalFormat(PATTERN).format(decimal.multiply(HUNDRED));
        gen.writeObject(value + "%");
    }
}
